;
(function ($) {

    /**
     * 程序中可能用到的时间计数
     */
    var timeInt = -1;

    /**
     * 弹出层的全局参数
     */
    var global;

    /**
     * 弹出层的可选参数
     */
    var options;

    /**
     * 遮罩层的默认选项
     */
    var defaultLockerOptions = {
        scope:'document',
        color:'transparent',
        opacity:0.5
    };
    /**
     * 弹出层的默认选项
     * 弹出内容的显示方式:
     * 1.有基本样式：关闭按钮，拖动栏，边框,里面加内容
     * 2.无任何样式，只有内容
     * 3.内容被iframe包裹吗
     */
    var defaultPopupOptions = {
        width:'auto',
        height:'auto',
        overflow:'auto',
        bindCss:'yes',
        wrapIframe:'no',
        options:{
            dragable:'yes',
            modal:'yes',
			skin:{
				color:'yellow',
				borer:"1",
				height:'42'
			},
            resizable:'no',
            sourceType:'diy',// 程序指定，页面的某个元素内容，代码片段url,ajax
            sourceValue:'Hello,this is popup content.'
    	}
    };


	/**
	 * 主调用接口
	 */
	$.lockScreen = function (opts) {
	    _lockScreen(opts);
	};
	$.removeLockScreen = function () {
	    _removeLockScreen();
	};
	$.popopLayer = function (opts) {
	    _popupLayer(opts);
	};
	$.closeLayer = function () {
	    _closeLayer();
	};
	
	/**
	 * 便捷调用接口
	 */
	/**
	 * 
	 */
	

	function _lockScreen(opts) {
	    opts = $.extend(defaultLockerOptions, opts.locker || {});
	    var documentWidth = $(document).width() + "px";
	    var documentHeight = $(document).height() + "px";
	    var s = "";
	    if ($.browser.msie) {
	    	s = "<div id='popup_locker' style = 'position:absolute;width:"+documentWidth+";height:"+documentHeight+";top:0px;left:0px;z-index:1000;zoom:1;background-color:"+opts.color+";filter:alpha(opacity="+parseInt(opts.opacity*100)+");'>";
	    } else {
	    	s = "<div id='popup_locker' style='position:absolute;width:"
	            + documentWidth
	            + ";height:"
	            + documentHeight
	            + ";top:0px;left:0px;background-color:"
	            + opts.color
	            + ";background-repeat:repeat-x;opacity:"
	            + opts.opacity + ";z-index:1000'>";
	    }
	    s = s + " <span></span>";
	    s = s + "</div>";
	    $(document.body).append(s);
	}

	function _removeLockScreen() {
	    if ($("#popup_locker").length > 0) {
	        $("#popup_locker").remove();
	    }
	}

	function _popupLayer(opts) {
		/**
		 * 弹出遮罩层
		 */
	    $.lockScreen(opts);
	    /**
	     * 全局参数
	     */
	    global = $.extend(defaultPopupOptions, opts.popup || {});
	    /**
	     * 可选参数
	     */
	    options = defaultPopupOptions.options;
	    /**
	     * 弹出准备层
	     */
	    _showPrepareLayer();

	    /**
	     * 具体的渲染样式可能有两种，有默认的样式，无默认的样式 具体的内容可能来
	     * 自三个地方，作为参数提供，url，ajax
	     */
	    switch(options.sourceType){
	    	case 'diy':
	    		_popupLayerByDIY(options.sourceValue);
	    		break;
	    	case 'url':
	    		_popupLayerByUrl(options.sourceValue);
	    		break;
	    	case 'ajax':
	    		_popupLayerByAjax(options.sourceValue);
	    		break;
	    }
	}
	
	function _closeLayer() {
	    _removeLockScreen();
	    $("#popup_layer").remove();
	}
	
	function _showPrepareLayer() {
	    var width = 300;
	    var height = 185;
	    var left = ($(window).width() - width) / 2 + $(window).scrollLeft();
	    var top = ($(window).height() - height) / 2 + $(window).scrollTop();
	    var s = "<div id='popup_prepare' style='position:absolute;width:"
	        + width + "px;height:" + height + "px;top:" + top + "px;left:"
	        + left + "px;background-color:#9acd32;z-index:1002' >";
	    s = s + " <a style = 'position:absolute;left:282px;top:-4px;font-size:28px;line-height:28px;text-decoration:none' href = 'javascript:$._closePopupPrepare()' > X </a>";
	    s = s + " <div style = 'display:block;position:relative;text-align:center' > <span>loading <span type='progress'>...</span> </span> < /div>";
	    s = s + "</div>";
	    $(document.body).append(s);
	    var halfLeft = (width - $("#popup_prepare").find("div").width()) / 2;
	    var halfTop = (height - $("#popup_prepare").find("div").height()) / 2;
	    var pDiv = $("#popup_prepare");
	    pDiv.find("div").css("left", halfLeft);
	    pDiv.find("div").css("top", halfTop);
	    pDiv.show();
	    _toggleProgress();
	}
	
	function _closePopupPrepare() {
	    if ($("#popup_prepare").length > 0) {
	        $("#popup_prepare").remove();
	    }
	}
	
	function _toggleProgress() {
	    timeInt = setInterval(function () {
	        if ($("#popup_prepare span span:visible").length == 0) {
	            $("#popup_prepare span span").show();
	        } else {
	            $("#popup_prepare span span").hide();
	        }
	    }, 800);
	};
	
	/**
	 * 通过程序指定内容
	 */
	function _popupLayerByDIY(content) {
	    _showPopupLayerContent(content);
	}
	
	/**
	 * 通过url来获取内容
	 */
	function _popupLayerByUrl(url) {
	    var bodyContent = "";
	    $(document.body).append("<iframe id='contentIframe' name='contentIframe' src='" + url + "' style='display:none'></iframe>");
	    var win = window.frames['contentIframe'];
	    win.onload = function () {
	        bodyContent = win.document.body.innerHTML || "";
	        _showPopupLayerContent(bodyContent);
	        $("#contentIframe").remove();
	    };
	    return bodyContent;
	}
	
	/**
	 * 通过ajax来获取页面
	 */
	function _popupLayerByAjax(url) {
	    $.ajax({
	        cache:false,
	        dataType:'html',
	        type:'get',
	        url:url,
	        success:function (xhr) {
	        	_showPopupLayerContent(xhr);
	        }
	    });
	}
	
	/**
	 * 需使用全局参数和可选参数
	 */
	function _showPopupLayerContent(content) {
		var boxModel = _getWidthHeight_LeftTop(content);
		var width = boxModel[0];
		var height = boxModel[1];
		var left = boxModel[2];
		var top = boxModel[3];
		
	    var head = "";
	    var borderColor = options.skin.color;
	    if (global.bindCss === 'yes') {
	        var result = _getHead(width, height);
	        head = result[0];
	        width = result[1];
	        height = result[2];
	    }
	
	    var s = "<div id='popup_layer' style='position:absolute;width:" + width
	        + "px;height:" + height + "px;top:" + top + "px;left:" + left
	        + "px;border:1px " + borderColor + " solid;z-index:1002;'>";
	    s = s + head;
	    s = s + " <div name='contentWrap' style = 'text-align:center;width:"+width+"px;height:"+(height-options.skin.height)+"px;overflow:auto' > ";
	    if (global.wrapIframe === 'yes') {
	        s = s + "<iframe name='wrapIframe' id='wrapIframe' src='' width = '"+width+"px'  heigth = '"+(height-options.skin.height)+"px' scrolling = 'auto' > ";
	        s = s + "</iframe>";
	    } else {
	        s = s + content;
	    }
	    s = s + " </div>";
	    s = s + "</div>";
	    _closePopupPrepare();
	    $(document.body).append(s);
	
	    if (global.wrapIframe === 'yes') {
	        var win = window.frames['wrapIframe'];
	        win.onload = function () {
	            bodyContent = win.document.body.innerHTML = content;
	            if (global.bindCss === 'yes') {
	            	//修正关闭按钮到右侧
	                _dragable();
	            }
	        };
	    }
	    else {
	        if (global.bindCss === 'yes') {
	        	//修正关闭按钮到右侧
	        	var closeButton = $("div.hd .close");
	        	var width = closeButton[0].offsetWidth;
	        	var height = closeButton[0].offsetHeight;
	        	var left = $("#popup_layer")[0].offsetWidth - width - 1;
	        	closeButton.css("left",left);
	            _dragable();
	        }
	    }
	
	}
	
	function _getWidthHeight_LeftTop(content){
		var result = [];
	    var width = 0;
	    var height = 0;
	    if (global.width === 'auto' && global.height === 'auto') {
	        /**
	         * 先增加这个节点，再决定width，height,这里设置position为absolute，目的是使用其包裹性，保留信息高宽的真实性
	         */
	        var s = "<div name='contentWrap' style='position:absolute'>";
	        s = s + content;
	        s = s + "</div>";
	        $(document.body).append(s);
	        var width = $("div[name=contentWrap]")[0].offsetWidth;
	        var height = $("div[name=contentWrap]")[0].offsetHeight;
	    } else if (global.width === 'auto' && global.height != 'auto') {
	        var s = "<div name='contentWrap' style='position:absolute'>";
	        s = s + content;
	        s = s + "</div>";
	        $(document.body).append(s);
	        width = $("div[name=contentWrap]")[0].offsetWidth;
	        height = global.height;
	    } else if (global.width != 'auto' && global.height === 'auto') {
	        var s = "<div name='contentWrap' style='position:absolute'>";
	        s = s + content;
	        s = s + "</div>";
	        $(document.body).append(s);
	        width = global.width;
	        height = $("div[name=contentWrap]")[0].offsetHeight;
	    } else if (global.width != 'auto' && global.height != 'auto') {
	        width = global.width;
	        height = global.height;
	    }
	    if ($("div[name=contentWrap]").length > 0) {
	        $("div[name=contentWrap]").remove();
	    }		
	    var left = ($(window).width() - width) / 2 + $(window).scrollLeft();
	    var top = ($(window).height() - height) / 2 + $(window).scrollTop();
	    result.push(width);
	    result.push(height);
	    result.push(left);
	    result.push(top);
	    return result;
	}
	
	/**
	 * 获取头部的代码，需要使用局部参数
	 */
	function _getHead(width, height) {
	    var result = [];
	    var head = "";  
	    var bgColor = options.skin.color;
	    var headHeight = options.skin.height;   
	    var closeHeight = parseInt(headHeight)+2;
        height = parseInt(height) + parseInt(headHeight);
        var closeStyle = "position:absolute;text-decoration:none;color:gray;";
        closeStyle = closeStyle + "font-style:normal;";
        closeStyle = closeStyle + "font-variant: normal;";
        closeStyle = closeStyle + "font-size:"+closeHeight+"px;";
        closeStyle = closeStyle + "font-weight:normal;";
        closeStyle = closeStyle + "font-family:Arial,Verdana,Sans-serif;";
        closeStyle = closeStyle + "line-height:"+closeHeight+"px;";
        
        head = "	   <div class='hd' style = 'background-color:"+bgColor+";height:"+headHeight+"px;width:100%' > ";
        head = head + "    <a class='close' href = 'javascript:$.closeLayer()' style = '"+closeStyle+"' > X </a>";
        head = head + "</div>";
	
	    result.push(head);
	    result.push(width);
	    result.push(height);
	    return result;
	}
	
	/**
	 * 对如果捆绑了样式，并且开启了拖动，这里是拖动的代码
	 */
	function _dragable() {
	    var popup = $("#popup_layer");
	    var hd = $("#popup_layer .hd");
	    var moving = false;
	    hd.mousedown(function (e) {
	        moving = true;
	        hd.css("cursor", "move");
	        var originX = e.clientX;
	        var originY = e.clientY;
	        var originLeft = parseInt(popup[0].style.left);
	        var originTop = parseInt(popup[0].style.top);
	        $(document.body).mousemove(function (e) {
	            if (moving) {
	                var toX = e.clientX;
	                var toY = e.clientY;
	                var newLeft = originLeft + (toX - originX);
	                var newTop = originTop + (toY - originY);		                
	                popup[0].style.left = newLeft + "px";
	                popup[0].style.top = newTop + "px";
	            }
	        });
	        $(document.body).mouseup(function (e) {
	            if (moving) {
	                hd.css("cursor", "default");
	                moving = false;
	            }
	        });
	    });	    
	}
	
})(jQuery);
	
	
